/**
 *
 */
package com.ce.pms.customer.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.DataException;

import com.ce.pms.base.dao.impl.PmsBaseDaoImpl;
import com.ce.pms.customer.dao.IIndividualDao;
import com.ce.pms.customer.model.IdTypeDO;
import com.ce.pms.customer.model.IndividualDO;

/**
* 功能描述:
* <p>版权所有：中企动力
* <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
*
* @author  付湘辉
* @Created on  2008-05-26
*/
public class IndividualDaoImpl extends PmsBaseDaoImpl<IndividualDO> implements IIndividualDao {

	/**
	 *
	 * 功能描述: 添加一个个人信息
	 *
	 * @author 付湘辉
	 * Created on:2008-6-20
	 *
	 * 修改原因：
	 * @param individualDO
	 * @return IndividualDO
	 */
	public IndividualDO addIndividual(IndividualDO individualDO) {
		return this.saveObject(individualDO);
	}

	/**
	 *
	 * 功能描述: 根据id查询一个个人信息
	 *
	 * @author 付湘辉
	 * Created on:2008-6-20
	 *
	 * 修改原因：
	 * @param id
	 * @return IndividualDO
	 */
	public IndividualDO findById(Long id) {
		return super.findById(id);
	}

	public IndividualDO findByIdentity(IdTypeDO idType, String idNumber) {
		Criteria cr = this.criteriaFindUniqueBy("idType", idType);
		cr.add(Restrictions.eq("idNumber",idNumber));
		return (IndividualDO) this.findUnique(cr);
	}


	/**
	 * Function:<p>根据关系类型编号和参与人ID查询个人信息记录，
	 * 				根据业务要求决定记录的唯一性,如果查询的记录
	 * 				超过一条将抛出异常，如果没有找到，将返回NULL</p>
	 * @param participantId
	 * @param relationTypeCode
	 * @return
	 * Create author:罗军林
	 * Create on:2008-6-20
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public IndividualDO queryIndividualDOByRelationTypeCode(Long participantId,String relationTypeCode){
		StringBuffer hql=new StringBuffer("FROM IndividualDO as ind WHERE ind.participantId in ")
				.append("(SELECT prd.participant2.participantId FROM ParticipantRelationDO as prd ")
				.append("WHERE prd.participant1.participantId=:participantId " )
				.append("AND prd.relationType.relationTypeCode=:relationTypeCode)");
		if(participantId==null || relationTypeCode==null){
			return null;
		}else{
			Query query=this.createQuery(hql.toString());
			query.setLong("participantId",participantId);
			query.setString("relationTypeCode", relationTypeCode);
			List list=query.list();
			if(list.size()>1){
				throw new DataException("There are one more record! ", null);
			}else if(list.size()<1){
				return null;
			}else{
				return (IndividualDO)(list.get(0));
			}
		}
	}
}
